package com.xpec.c4.service.module.datacenter.player;

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ms.player.Player;
import com.ms.player.UpdateAttribute;
import com.xpec.c4.db.dao.PlayerDAO;
import com.xpec.c4.game.character.PlayerManager;
import com.xpec.c4.game.datamanager.ResultNo;
import com.xpec.c4.game.datamanager.agent.PlayerData;
import com.xpec.c4.service.module.datacenter.DCAsyncCommand;

/**
 * 
 * @author TW15010
 *
 */
public class UpdatePlayerDataAsync extends DCAsyncCommand {

	private static final Log log = LogFactory.getLog(UpdatePlayerDataAsync.class);

	PlayerDataManager dataManager;

	@Override
	public void asyncExecute() {
		Player player = (Player) dataInfo.getData();
		
		ArrayList<UpdateAttribute> updatedAttrList = null;
		if (dataInfo instanceof PlayerData) {
			if (((PlayerData) dataInfo).getUpdateAttrList() != null) {
				updatedAttrList = ((PlayerData) dataInfo).getUpdateAttrList().getUpdateList();
			}
		}
		
		boolean res = false;

		try {
			if (updatedAttrList == null) {
				res = PlayerManager.getInstance().updatePlayerToDB(player);
			} else {
				res = PlayerDAO.updatePlayerFromAttrList(player.getGuid().toString(), updatedAttrList, player.getUserType());
			}
		} catch (RuntimeException e) {
			log.error("cannot update player:" + player.getGuid(), e);
			resultCode = ResultNo.DB_OPERATION_FAILED;
			return;
		}

		if (res) {
			resultCode = ResultNo.OK;
		} else {
			resultCode = ResultNo.DB_OPERATION_FAILED;
		}

		return;
	}

	@Override
	public void execute() {
		// callback
		if (dataManager != null) {
			dataManager.updateDataCallback(resultCode, dataInfo, srcModuleID, true);
		}
	}

	public void setDataManager(PlayerDataManager dataManager) {
		this.dataManager = dataManager;
	}
}
